package com.dataextend.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dataextend.entity.RequestUserTag;
import com.dataextend.mapper.cluster.UserProfileMapper;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 *  用户行为时间轴查询
 */
@Service
public class UserActTimelineService {
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Value("${usertimeline_data.usertimeline_data.index}")
    private String userActTimeIndex;
    @Value("${usertimeline_data.usertimeline_data.source_field}")
    private String userActTimeField;
    @Value("${usertimeline_data.usertimeline_data.type}")
    private String type;
    @Autowired
    private UserProfileMapper userProfileMapper;

    private JSONArray elasticsearchCalculate(String cookieid){
        Map<String, String> codeMaps = new HashMap();
        List<JSONObject> events = userProfileMapper.getEventModel();
        for (JSONObject event:events) {
            String eventCode = event.getString("event_code");
            String eventName = event.getString("event_name");
            codeMaps.put(eventCode, eventName);
        }

        //创建搜索请求对象
        SearchRequest searchRequest = new SearchRequest(userActTimeIndex);
        String[] source_field_array = userActTimeField.split(",");

        //设置搜索类型
        searchRequest.types(type);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.fetchSource(source_field_array, new String[]{});

        //创建布尔查询对象
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("distinct_id", cookieid));
        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);
        ArrayList usertags = new ArrayList();

        try {
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest);
            SearchHits hits = searchResponse.getHits();
            SearchHit[] searchHits = hits.getHits();
            for (SearchHit hit : searchHits){
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                usertags = (ArrayList) sourceAsMap.get("act_path");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        JSONArray returnArray = new JSONArray();
        for (Object usertag : usertags){
            JSONObject mergeResult = new JSONObject(true);
            String keyValue = usertag.toString().replace("{","").replace("}","");
            String eventTime = keyValue.split(",")[0].replace("time=", "");
            String eventName_ = keyValue.split(",")[1].replace("event=","").replace(" ","");
            String eventName = codeMaps.get(eventName_);
            mergeResult.put("eventName",eventName);
            mergeResult.put("eventTime",eventTime);
            returnArray.add(mergeResult);
        }

        System.out.println(returnArray);
        return returnArray;
    }



    public JSONObject findUser(RequestUserTag requestUserTag){
        JSONArray cookieInfo =elasticsearchCalculate(requestUserTag.getCookieid());
        JSONObject mergeResult = new JSONObject(true);
        mergeResult.put("cookieId", requestUserTag.getCookieid());
        mergeResult.put("allTags", cookieInfo);
        return mergeResult;
    }
}
